package io.geekidea.boot.util.dingtalk;

import cn.hutool.http.HttpStatus;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponseBody;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthTokenUtil {

  /**
   * 使用 Token 初始化账号Client
   *
   * @return Client
   * @throws Exception
   */
  private static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
    config.protocol = "https";
    config.regionId = "central";
    return new com.aliyun.dingtalkoauth2_1_0.Client(config);
  }

  /**
   * https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app
   *
   * @param appKey
   * @param appSecret
   * @return
   */
  public static GetAccessTokenResponseBody getAccessToken(String appKey, String appSecret) {
    com.aliyun.dingtalkoauth2_1_0.Client client;
    try {
      client = createClient();
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return null;
    }
    com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
        .setAppKey(appKey)
        .setAppSecret(appSecret);
    try {
      GetAccessTokenResponse resp = client.getAccessToken(getAccessTokenRequest);
      if (resp.getStatusCode() == HttpStatus.HTTP_OK) {
        return resp.getBody();
      }
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
    }
    return null;
  }
}
